package com.atguigu.ssyx.search.service.impl;

import com.atguigu.ssyx.client.product.ProductFeignClient;
import com.atguigu.ssyx.common.exception.SsyxException;
import com.atguigu.ssyx.common.result.ResultCodeEnum;
import com.atguigu.ssyx.enums.SkuType;
import com.atguigu.ssyx.model.product.Category;
import com.atguigu.ssyx.model.product.SkuInfo;
import com.atguigu.ssyx.model.search.SkuEs;
import com.atguigu.ssyx.search.repository.SkuRepository;
import com.atguigu.ssyx.search.service.SkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 杨林
 * @create 2023-08-02 10:34 星期三
 * description:
 */
@Service
@Slf4j
public class SkuServiceImpl implements SkuService {

    @Autowired
    private SkuRepository skuRepository;
    
    @Autowired
    private ProductFeignClient productFeignClient;
    
    /**
     * 商品上架：将商品信息放入到ES中
     * @param skuId
     */
    @Override
    public void upperGoods(Long skuId) {
        //将商品信息保存到ES中
        log.info("开始将商品{}存入ES中",skuId);
        SkuEs skuEs = new SkuEs();
        //查询SKU信息
        SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);
        if (skuInfo == null){
            //如果未查到对应的SkuInfo信息，就返回数据异常
            throw new SsyxException(ResultCodeEnum.DATA_ERROR);
        }
        //获取商品的categoryId并查询对应的商品分类信息
        Long categoryId = skuInfo.getCategoryId();
        Category category = productFeignClient.getCategory(categoryId);
        if (category != null){
            //如果商品分类信息不为空，则封装商品分类信息
            skuEs.setCategoryId(categoryId);
            skuEs.setCategoryName(category.getName());
        }
        //封装SKU基本信息
        skuEs.setId(skuInfo.getId());
        skuEs.setKeyword(skuInfo.getSkuName() + "," + skuEs.getCategoryName());
        skuEs.setWareId(skuInfo.getWareId());
        skuEs.setIsNewPerson(skuInfo.getIsNewPerson());
        skuEs.setImgUrl(skuInfo.getImgUrl());
        skuEs.setTitle(skuInfo.getSkuName());
        //判断当前商品是否是秒杀商品
        if (skuInfo.getSkuType() == SkuType.COMMON.getCode()){
            //如果当前商品不是秒杀商品，则商品的价格，库存，销量，限购个数为普通商品的值
            //普通商品
            skuEs.setSkuType(0);
            skuEs.setPrice(skuInfo.getPrice().doubleValue());
            skuEs.setStock(skuInfo.getStock());
            skuEs.setPerLimit(skuInfo.getPerLimit());
        }else {
            //todo 当前商品为秒杀商品
            
        }
        skuRepository.save(skuEs);
        log.info("当前商品{}已经成功存入到ES中",skuId);
    }

    /**
     * 商品下架，将商品信息从ES中删除
     * @param skuId
     */
    @Override
    public void lowerGoods(Long skuId) {
        //从ES中删除商品信息
        skuRepository.deleteById(skuId);
    }
}
